﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using System.Data;


namespace HTToPdf
{
    class XSPDFPlus
    {
        Common Init = new Common();

        private static Document doc;
        private static PdfPTable table;
        string[] content;
        float[] SetTotalWidth;//设定每列宽度
        int[] BorderSide;//设定每列边框
        int[] HAlign;
        string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory);
        public Common.Model model = null;

        private static BaseFont titleBaseFont = BaseFont.CreateFont("C://WINDOWS//Fonts//simhei.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);//黑体

        /// <summary>
        /// 创建PDF
        /// </summary>
        /// <param name="dtSource">数据源</param>
        /// <returns></returns>
        public bool CreatePDF(string SaveFileName, Common.Model model, DataTable dtSource)
        {
            this.model = model;
            bool flag = false;
            try
            {
                doc = new Document(PageSize.A4, 10, 10, 10, 10);//定义一个Document，并设置页面大小为A4，竖向
                MemoryStream pdfMS = new MemoryStream();
                PdfWriter writer = PdfWriter.GetInstance(doc, pdfMS);//PDF内容放入到流中
                doc.Open();

                PageHeader();

                int emptyRow = 10;//如果table的行数小于20行，那么剩余部分显示空白行
                int sortNo = 0;//序号
                int Total = 10;

                SetTotalWidth = new float[] { 30, 100, 90, 30, 60, 50, 60, 160 };//设定每列宽度
                BorderSide = new int[] { 0, 0, 0, 0, 0, 0, 0, 0 };//设定每列边框
                HAlign = new int[] { Element.ALIGN_CENTER, Element.ALIGN_CENTER, Element.ALIGN_CENTER, Element.ALIGN_CENTER, Element.ALIGN_RIGHT, Element.ALIGN_RIGHT, Element.ALIGN_RIGHT, Element.ALIGN_MIDDLE };
                if (dtSource.Rows.Count > 0)
                {
                    for (int i = 0; i < dtSource.Rows.Count; i++)
                    {
                        if (i % Total == 0 && i != 0)
                        {
                            PageFooter();
                            doc.NewPage();
                            PageHeader();
                        }

                        sortNo++;
                        content = new string[] { (i + 1).ToString(), dtSource.Rows[i]["spmch"].ToString(), dtSource.Rows[i]["shpgg"].ToString(), dtSource.Rows[i]["dw"].ToString(), dtSource.Rows[i]["shl"].ToString(), dtSource.Rows[i]["dj"].ToString(), dtSource.Rows[i]["hsje"].ToString(), dtSource.Rows[i]["shengccj"].ToString() };
                        table = AddTableHeader(content, SetTotalWidth, BorderSide, new Font(titleBaseFont, 10), HAlign);
                        doc.Add(table);
                    }
                }
                if (dtSource.Rows.Count % Total != 0)//说明数据源不足10行
                {
                    emptyRow = 11 - dtSource.Rows.Count % Total;//如果为负数，说明不需要生成空白行
                    for (int i = 0; i < emptyRow; i++)
                    {
                        content = new string[] { (dtSource.Rows.Count + i + 1).ToString(), "", "", "", "", "", "", "" };
                        table = AddTableHeader(content, SetTotalWidth, BorderSide, new Font(titleBaseFont, 10), HAlign);
                        doc.Add(table);
                    }
                }

                PageFooter();

                doc.Close();
                byte[] fileByte = pdfMS.GetBuffer();
                FileStream fs = new FileStream(SaveFileName, FileMode.Create);
                BinaryWriter bw = new BinaryWriter(fs);
                bw.Write(fileByte);
                bw.Close();
                fs.Close();
                flag = true;
            }
            catch (Exception ex)
            {
                Init.WriteLog(ex.ToString(), true);
            }
            return flag;
        }

        #region 文件头
        public void PageHeader()
        {
            CreateEmptyRow(1);//生成一行空行
            AddHeaderTitleContent("四川金仁医药集团有限公司销售合同", 1, 15, Font.BOLD);//添加表头
            CreateEmptyRow(1);//生成一行空行
            content = new string[] { "签约地点：", "", "签约时间：", model.rq, "川金药销售合同编号：", model.djbh, "" };
            SetTotalWidth = new float[] { 80, 100, 80, 80, 140, 120, 20 };//设定每列宽度
            BorderSide = new int[] { 15, 13, 15, 13, 15, 13, 15 };//设定每列边框
            HAlign = new int[] { Element.ALIGN_RIGHT, Element.ALIGN_LEFT, Element.ALIGN_RIGHT, Element.ALIGN_LEFT, Element.ALIGN_RIGHT, Element.ALIGN_LEFT, Element.ALIGN_RIGHT };
            table = AddTableHeader(content, SetTotalWidth, BorderSide, new Font(titleBaseFont, 13), HAlign);
            doc.Add(table);

            CreateEmptyRow(1);//生成一行空行

            content = new string[] { "序号", "商品名称", "商品规格", "单位", "数量", "单价", "金额", "生产企业" };
            SetTotalWidth = new float[] { 30, 100, 90, 30, 60, 50, 60, 160 };//设定每列宽度
            BorderSide = new int[] { 0, 0, 0, 0, 0, 0, 0, 0 };//设定每列边框
            HAlign = new int[] { Element.ALIGN_CENTER, Element.ALIGN_CENTER, Element.ALIGN_CENTER, Element.ALIGN_CENTER, Element.ALIGN_CENTER, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE, Element.ALIGN_MIDDLE };
            table = AddTableHeader(content, SetTotalWidth, BorderSide, new Font(titleBaseFont, 10), HAlign);
            doc.Add(table);
        }
        #endregion

        #region 文件尾
        public void PageFooter()
        {
            SetTotalWidth = new float[] { 130, 230, 60, 160 };//设定每列宽度
            BorderSide = new int[] { 0, 0, 0, 0 };//设定每列边框
            HAlign = new int[] { Element.ALIGN_RIGHT, Element.ALIGN_LEFT, Element.ALIGN_RIGHT, Element.ALIGN_LEFT };
            content = new string[] { "合计金额：", Init.NumtoChinese(decimal.Parse(model.hsje)), model.hsje, "" };
            table = AddTableHeader(content, SetTotalWidth, BorderSide, new Font(titleBaseFont, 10), HAlign);
            doc.Add(table);
            // CreateEmptyRow(1);//生成一行空行
            string[] Title = { "一、发货方式：", "运费承担：", "结算期限：", "结算方式：", "增值税票：" };
            string[] Content = { model.thfs, model.yunfcd, model.jsms, model.fkfs, model.faplx + "。" };
            AddPartnerContent(Title, Content);
            string contents =
                 // "一、发货方式：" + header[4] + "   运费承担：" + header[5] + "   结算期限：" + header[6] + "   结算方式：" + header[7] + "   增值税票：" + header[8] + "\r\n"
                  "二、特别约定：\r\n"
                + "  1、对方须提供：企业营业执照、经营许可证及其它相关资质等有效证件复印件并加盖鲜章。\r\n"
                + "  2、合同项下货款汇至本公司指定银行账号，不得汇至合同规定以外任何银行账号，或以任何理由支取现金，除取得供方财务部门书面通知并收到其出具的正式收据方可办理。\r\n"
                + "  3、合同项下产品，在没有取得供方销售部门和财务部门联合书面通知下，并签订变更合同的，不得以任何理由调往它处，用以冲减合同货款。\r\n"
                + "  4、验收标准、方式、提出异议期限；数量按送货单当场验收或提出异议，质量在收货15日内提出书面异议并附依据。\r\n"
                + "  5、合理损耗及计算方法：损耗按药品运输有关规定，由购方出具破损证明书交供方办理退款或补货手续，不得从货款中扣除。\r\n"
                + "三、质量保证条款：\r\n"
                + "  1、药品质量符合法定质量标准和有关质量要求；\r\n"
                + "  2、药品附每批次质检报告书和产品合格证；\r\n"
                + "  3、进口药品应（附口岸药检所报告，注册证并加盖本企业鲜章）；\r\n"
                + "  4、药品包装符合有关规定和货物运输要求。\r\n"
                + "四、本合同经双方签字、盖章生效。\r\n"
                + "五、违约责任：按《中华人民共和国经济合同法》及有关规定处理。\r\n"
                + "六、解决合同纠纷方式：双方协商不成时，在供方所在地人民法院通过诉讼方式解决。\r\n"
                + "七、其它约定事由：__________________________________________\r\n\r\n"
                + "";
            AddHeaderTitleContent(contents, 0, 10, Font.NORMAL);//添加表头

            SetTotalWidth = new float[] { 100, 190, 100, 190 };//设定每列宽度
            BorderSide = new int[] { 0, 0, 0, 0 };//设定每列边框
            HAlign = new int[] { Element.ALIGN_RIGHT, Element.ALIGN_LEFT, Element.ALIGN_RIGHT, Element.ALIGN_LEFT };
            content = new string[] { "供方（章）", "四川金仁医药集团有限公司", "购方（章）", model.dwmch };
            table = AddTableHeader(content, SetTotalWidth, BorderSide, new Font(titleBaseFont, 12), HAlign);
            doc.Add(table);

            string[] tablelist = { "地址", "开户银行", "账号", "统一信用代码", "联系电话", "授权签约人" };
            string[] myvalue = { "成都市金牛区金丰路112号六幢1、2、3、4层5、6号", "四川天府银行股份有限公司成都金牛支行", "651001732000000168", "91510106768621824L", "028-83420240", model.username };
            string[] cutvalue = { model.dzhdh, model.khyh, model.yhzhh, model.shh, "", "" };

            for (int i = 0; i < tablelist.Count(); i++)
            {
                content = new string[] { tablelist[i], myvalue[i], tablelist[i], cutvalue[i] };
                table = AddTableHeader(content, SetTotalWidth, BorderSide, new Font(titleBaseFont, 12), HAlign);
                doc.Add(table);
            }
            iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(@path + "\\sitamp.dll");
            img.SetAbsolutePosition((doc.PageSize.Width / 2) - 150, (doc.PageSize.Height / 2) - 340);
            img.ScaleToFit(110F, 110F);
            //img.GrayFill = 20;
            doc.Add(img);
        }
        #endregion

        #region 生成水印
        /// <summary>
        /// 设置pdf图片水印
        /// </summary>
        /// <param name="imgPath">水印图片路径</param>
        /// <param name="filePath">需要添加水印的pdf文件</param>
        /// <param name="outfilePath">添加完成的pdf文件</param>
        /// <returns></returns>
        public static bool SetImgWaterMark(string imgPath, string filePath, string outfilePath)
        {
            PdfReader pdfReader = null;
            PdfStamper pdfStamper = null;
            FileStream fileStream = null;
            try
            {
                pdfReader = new PdfReader(filePath);
                fileStream = new FileStream(outfilePath, FileMode.Create);
                pdfStamper = new PdfStamper(pdfReader, fileStream);
                int total = pdfReader.NumberOfPages;
                Rectangle psize = pdfReader.GetPageSize(1);
                float width = psize.Width;
                float height = psize.Height;
                PdfContentByte content;
                //获取水印图片
                Image image = Image.GetInstance(imgPath);
                image.SetAbsolutePosition((doc.PageSize.Width / 2) - 150, (doc.PageSize.Height / 2) - 340);
                image.ScaleToFit(110F, 110F);
                image.GrayFill = 20;

                for (int i = 1; i <= total; i++)
                {
                    content = pdfStamper.GetOverContent(i);//在内容上方加水印
                    //content = pdfStamper.GetUnderContent(i);//在内容下方加水印
                    content.AddImage(image);
                }
                return true;
            }
            catch (Exception ex)
            {
                //Common.WriteLogs(ex.ToString(), true);
                outfilePath = "";
                return false;
            }
            finally
            {
                if (pdfStamper != null)
                {
                    pdfStamper.Close();
                }
                if (pdfReader != null)
                {
                    pdfReader.Close();
                }
                if (fileStream != null)
                {
                    fileStream.Close();
                    fileStream.Dispose();
                }
            }
        }
        #endregion


        #region 生成N行空白行
        private static void CreateEmptyRow(int emptyRowNum)
        {
            for (int i = 0; i < emptyRowNum; i++)
            {
                doc.Add(new Paragraph(" "));
            }
        }
        #endregion

        #region 生成标题
        /// <summary>
        /// 
        /// </summary>
        /// <param name="content">内容</param>
        /// <param name="Alignment">对齐 0居左，1居中，2居右</param>
        /// <param name="FontSize">字体大小</param>
        /// <param name="style">样式</param>
        private static void AddHeaderTitleContent(string content, int Alignment, int FontSize, int style)
        {
            Paragraph p = new Paragraph(content, new Font(titleBaseFont, FontSize, style));
            p.Alignment = Alignment;
            doc.Add(p);
        }
        #endregion

        #region 生成表格头
        private static PdfPTable AddTableHeader(string[] content, float[] colSet, int[] BorderSide, Font font, int[] horizontalAlignment)
        {
            int count = content.Count();
            PdfPTable table = new PdfPTable(count);//列的table
            //添加表格列头               
            //table.SetTotalWidth(SetTotalWidth);
            table.SetWidthPercentage(colSet, PageSize.A4);
            for (int i = 0; i < count; i++)
            {
                table.AddCell(GetPdfCell(content[i], font, horizontalAlignment[i], BorderSide[i]));
            }
            return table;
        }
        #endregion

        #region 生成单元格
        private static PdfPCell GetPdfCell(string content, Font font, int horizontalAlignment, int BorderSide)
        {
            PdfPCell cell = new PdfPCell(new Paragraph(content, font));
            cell.HorizontalAlignment = horizontalAlignment;//水平位置
            cell.VerticalAlignment = Element.ALIGN_CENTER;//垂直居中
            cell.MinimumHeight = 18;//单元格的最小高度
            cell.NoWrap = false;
            cell.DisableBorderSide(BorderSide);
            return cell;
        }
        #endregion

        //四种字体
        private static Font fontMiddle = new Font(titleBaseFont, 10, Font.BOLD);
        private static Font fontSmallNoBold = new Font(titleBaseFont, 10);
        private static float IndentationLeft = 0;//距左边距

        private static void AddPartnerContent(string[] Title, string[] Content)
        {
            fontMiddle.SetStyle(Font.UNDERLINE);//文字下划线
            Paragraph content = new Paragraph();
            content.IndentationLeft = IndentationLeft;
            int Total = 0;
            for (int i = 0; i < Title.Count(); i++)
            {
                Chunk chunkName = new Chunk(Title[i], fontSmallNoBold);
                Chunk chunkText = string.IsNullOrEmpty(Content[i]) ? new Chunk(GetEmptyString(6, " / "), fontMiddle) : new Chunk(GetEmptyString(Content[i].Length + 6, Content[i]), fontMiddle);
                    content.Add(Total, chunkName);                    
                    Total++;
                    content.Add(Total, chunkText);  
                    Total++;
            }
            content.Alignment = 3;
            doc.Add(content);
        }
        //居中显示内容
        private static string GetEmptyString(int maxlength, string text)
        {
            int padding = (maxlength - text.Length * 2) / 2;
            string empty = string.Empty;
            for (int i = 0; i < padding; i++)
            {
                empty += " ";
            }
            return string.Format("{0}{1}{0}", empty, text);
        }
    }
}